package com.basic.modules.nykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.basic.common.utils.*;
import com.basic.modules.nykf.dao.RenewBatchDao;
import com.basic.modules.nykf.dao.RenewManageTwoMapper;
import com.basic.modules.nykf.entity.*;
import com.basic.modules.nykf.service.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.*;

@Service
public class RenewManageTwoServiceImpl implements RenewManageTwoService {

    @Autowired
    RenewManageTwoMapper renewManageTwoMapper;

    @Autowired
    RenewBatchService renewBatchService;

    @Autowired
    RenewShouService renewShouService;

    @Autowired
    RenewTuiService renewTuiService;

    @Autowired
    RenewDetailsService renewDetailsService;

    @Autowired
    @Lazy
    CustomerShopBusinessService customerShopBusinessService;

    @Autowired
    RenewBatchDao renewBatchDao;

    @Override
    public PageUtils getRenewYwList(ParamsModel<CustomerShopBusinessEntity> params) {
        IPage<Map> page = new Query<Map>().getPage(BeanUtil.beanToMap(params.getPage()));
        IPage<Map> renewYwList = renewManageTwoMapper.getRenewYwList(page, params.getCondition());
        return new PageUtils(renewYwList);
    }

    @Override
    public Map getScskList(Map map) {
        Map map1 = new HashMap();
        map1.put("renewBatchId", "");
        map1.put("skList", new ArrayList<>());
        Long customerShopBusinessId = Long.parseLong(map.get("customerShopBusinessId").toString());
        QueryWrapper<RenewBatchEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_shop_business_id", customerShopBusinessId);
        queryWrapper.eq("renew_index", 1);
        RenewBatchEntity renewBatch = renewBatchService.getOne(queryWrapper);
        if (renewBatch != null) {
            String renewBatchId = renewBatch.getRenewBatchId();
            RenewShouEntity renewShou = new RenewShouEntity();
            renewShou.setBatchId(renewBatchId);
            List<RenewShouEntity> list = renewShouService.getRenewShouList(renewShou);
            map1.put("renewBatchId", renewBatchId);
            map1.put("skList", list);
            return map1;
        } else {
            return map1;
        }
    }

    @Override
    public R postScsk(Map map) {
        String renewBatchId = map.get("renewBatchId").toString();
        Long customerShopBusinessId = Long.parseLong(map.get("customerShopBusinessId").toString());

        QueryWrapper<CustomerShopBusinessEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_shop_business_id", customerShopBusinessId);
        CustomerShopBusinessEntity ywObj = customerShopBusinessService.getOne(queryWrapper);

        boolean isCreateBatch = false;
        if (!"".equals(renewBatchId)) {
            // 校验这个首次付款有没有确认,已经确认了就不能再动收款了
            QueryWrapper<RenewBatchEntity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("renew_batch_id", renewBatchId);
            RenewBatchEntity renewBatch = renewBatchService.getOne(queryWrapper1);
            if (renewBatch.getRenewStatus() == 2) {
                return R.error("该批次已完成确认,无法修改收款记录");
            }
        } else {
            renewBatchId = getBatchId();
            isCreateBatch = true;
        }

        List<Map> scskList = (List<Map>) (map.get("scskList"));
        BigDecimal skjeCount = BigDecimal.ZERO;

        // 收款表
        for (int i = 0; i < scskList.size(); i++) {
            Map map1 = scskList.get(i);
            RenewShouEntity renewShou = new RenewShouEntity();
            renewShou.setBatchId(renewBatchId);
            renewShou.setSklxVal(map1.get("sklxVal").toString());
            renewShou.setSkztVal(map1.get("skztVal").toString());
            BigDecimal skje = new BigDecimal(map1.get("skje").toString());
            skjeCount = skjeCount.add(skje);
            renewShou.setSkje(skje);
            renewShou.setSksj(DateUtils.stringToDate(map1.get("sksj").toString(), DateUtils.DATE_PATTERN));
            renewShou.setSkqdVal(map1.get("skqdVal").toString());
            renewShou.setSfkpVal(map1.get("sfkpVal").toString());
            renewShou.setKpztVal(map1.get("kpztVal").toString());
            renewShou.setBz(map1.get("bz").toString());
            Long userId = CommonUtils.getUserId();
            renewShou.setCreateUserId(userId);

            if (map1.get("batchId") == null) {
                // 保存
                renewShouService.save(renewShou);
            } else {
                // 修改
                renewShou.setId(Long.parseLong(map1.get("id").toString()));
                renewShouService.updateById(renewShou);
            }
        }

        // 修改业务底薪
        CustomerShopBusinessEntity customerShopBusiness = new CustomerShopBusinessEntity();
        customerShopBusiness.setYwdx(skjeCount);
        customerShopBusiness.setCustomerShopBusinessId(customerShopBusinessId);
        customerShopBusinessService.updateById(customerShopBusiness);

        if (isCreateBatch) {
            createRenewOrder_yzf(ywObj, renewBatchId);
        }
        return R.ok("操作成功");
    }

    @Override
    public R createRenewOrder(Map map) {
        Long customerShopBusinessId = Long.parseLong(map.get("customerShopBusinessId").toString());
        CustomerShopBusinessEntity ywObj = customerShopBusinessService.getById(customerShopBusinessId);
        List<Integer> renewStatus = new ArrayList<>(Arrays.asList(0, 1));
        List<RenewBatchEntity> list = renewManageTwoMapper.getRenewBatchData(ywObj, renewStatus);
        // 整理批次数据,保证有一个已完成支付的订单和一个待续费的订单
        Boolean isInsert = arrangeBatchData(list, ywObj);
        if (isInsert == true) {
            list = renewManageTwoMapper.getRenewBatchData(ywObj, renewStatus);
        }
        return R.ok(list);
    }

    /**
     * 整理批次数据,用RenewBatchEntity对象里的renew_status字段
     * 没0没1,创建已支付、创建续费订单
     * 有1没0,完成首次付款,创建续费订单
     * 有1有0,无需处理
     */
    public Boolean arrangeBatchData(List<RenewBatchEntity> list, CustomerShopBusinessEntity customerShopBusinessEntity) {
        boolean isInsert = false;

        // 检查列表中是否包含特定状态的记录
        boolean hasStatus0 = list.stream().anyMatch(entity -> entity.getRenewStatus() == 0);
        boolean hasStatus1 = list.stream().anyMatch(entity -> entity.getRenewStatus() == 1);

        if (!hasStatus0 && !hasStatus1) {
            // 情况1: 没0没1,创建已支付、创建续费订单
            createRenewOrder_yzf(customerShopBusinessEntity, getBatchId());
            createRenewOrder_dxf(customerShopBusinessEntity, getBatchId());
            isInsert = true;
        } else if (hasStatus1 && !hasStatus0) {
            // 情况2: 有1没0,完成首次付款,创建续费订单
            createRenewOrder_dxf(customerShopBusinessEntity, getBatchId());
            isInsert = true;
        }
        return isInsert;
    }

    /**
     * 创建已支付订单
     */
    public void createRenewOrder_yzf(CustomerShopBusinessEntity ywObj, String renewBatchId) {
        RenewBatchEntity renewBatch = new RenewBatchEntity();
        renewBatch.setRenewBatchId(renewBatchId);
        renewBatch.setCustomerId(ywObj.getCustomerId());
        renewBatch.setSfmsVal(ywObj.getSfmsVal());
        renewBatch.setCustomerShopBusinessId(ywObj.getCustomerShopBusinessId());
        renewBatch.setRenewIndex(1);
        renewBatch.setYsfy(BigDecimal.ZERO);
        renewBatch.setYshz(BigDecimal.ZERO);
        renewBatch.setRenewStatus(1);
        renewBatchService.save(renewBatch);
        createRenewOrder_details(ywObj, renewBatchId, 1);
    }

    /**
     * 创建待续费订单
     */
    public void createRenewOrder_dxf(CustomerShopBusinessEntity ywObj, String renewBatchId) {
        RenewBatchEntity renewBatch = new RenewBatchEntity();
        renewBatch.setRenewBatchId(renewBatchId);
        renewBatch.setCustomerId(ywObj.getCustomerId());
        renewBatch.setSfmsVal(ywObj.getSfmsVal());
        renewBatch.setCustomerShopBusinessId(ywObj.getCustomerShopBusinessId());
        Integer renewIndex = renewBatchDao.getRenewIndex(ywObj);
        renewBatch.setRenewIndex(renewIndex);
        renewBatch.setYsfy(BigDecimal.ZERO);
        renewBatch.setYshz(BigDecimal.ZERO);
        renewBatch.setRenewStatus(0);
        renewBatchService.save(renewBatch);
        createRenewOrder_details(ywObj, renewBatchId, 0);
    }

    /**
     * 创建订单明细数据
     * type = 0是待续费
     * type = 1是已支付
     */
    public void createRenewOrder_details(CustomerShopBusinessEntity ywObj, String renewBatchId, int type) {
        QueryWrapper<CustomerShopBusinessEntity> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("customer_id", ywObj.getCustomerId());
        String sfmsVal = ywObj.getSfmsVal();
        queryWrapper2.eq("sfms_val", ywObj.getSfmsVal());
        if ("单独收费".equals(sfmsVal) || "临时业务".equals(sfmsVal)) {
            queryWrapper2.eq("customer_shop_business_id", ywObj.getCustomerShopBusinessId());
        }
        List<CustomerShopBusinessEntity> ywList = customerShopBusinessService.list(queryWrapper2);
        for (CustomerShopBusinessEntity customerShopBusinessEntity : ywList) {
            RenewDetailsEntity renewDetailsEntity = new RenewDetailsEntity();
            renewDetailsEntity.setRenewBatchId(renewBatchId);
            renewDetailsEntity.setCustomerShopBusinessId(customerShopBusinessEntity.getCustomerShopBusinessId());
            if (type == 1) {
                renewDetailsEntity.setYwkssj(customerShopBusinessEntity.getYwkssj());
                renewDetailsEntity.setYwjssj(customerShopBusinessEntity.getYwjssj());
                renewDetailsEntity.setRjzxl(customerShopBusinessEntity.getZxl());
            }
            renewDetailsService.save(renewDetailsEntity);
        }
    }

    @Override
    public R getRenewShouList(RenewShouEntity renewShouEntity) {
        List<RenewShouEntity> list = renewShouService.getRenewShouList(renewShouEntity);
        return R.ok(list);
    }

    @Override
    public R postSkList(Map map) {
        String batchId = map.get("skBatchId").toString();
        List<RenewShouEntity> skList = (List<RenewShouEntity>) map.get("skList");

        BigDecimal zfCount = BigDecimal.ZERO;
        for (int i = 0; i < skList.size(); i++) {
            ObjectMapper objectMapper = new ObjectMapper();
            RenewShouEntity renewShouEntity = objectMapper.convertValue(skList.get(i), RenewShouEntity.class);
            Long id = renewShouEntity.getId();
            if (id == null) {
                // 支付记录新增
                renewShouEntity.setBatchId(batchId);
                renewShouEntity.setCreateUserId(CommonUtils.getUserId());
                renewShouService.save(renewShouEntity);
            } else {
                // 支付记录修改
                renewShouService.updateById(renewShouEntity);
            }
            zfCount = zfCount.add(renewShouEntity.getSkje());
        }

        // 如果这个支付批次是已支付的(renew_status=1)
        RenewBatchEntity renewBatch = renewBatchService.getById(batchId);
        if (renewBatch.getRenewStatus() == 1) {
            // 修改业务底薪
            Long customerShopBusinessId = renewBatch.getCustomerShopBusinessId();
            CustomerShopBusinessEntity customerShopBusiness = new CustomerShopBusinessEntity();
            customerShopBusiness.setCustomerShopBusinessId(customerShopBusinessId);
            customerShopBusiness.setYwdx(zfCount);
            customerShopBusinessService.updateById(customerShopBusiness);
        }
        return R.ok(zfCount);
    }

    @Override
    public R getRenewTuiList(RenewTuiEntity renewTuiEntity) {
        List<RenewTuiEntity> list = renewTuiService.getRenewTuiList(renewTuiEntity);
        return R.ok(list);
    }

    @Override
    public R postTkList(Map map) {
        String batchId = map.get("tkBatchId").toString();
        List<RenewTuiEntity> tkList = (List<RenewTuiEntity>) map.get("tkList");

        BigDecimal tkCount = BigDecimal.ZERO;
        for (int i = 0; i < tkList.size(); i++) {
            ObjectMapper objectMapper = new ObjectMapper();
            RenewTuiEntity renewTuiEntity = objectMapper.convertValue(tkList.get(i), RenewTuiEntity.class);
            Long id = renewTuiEntity.getId();
            if (id == null) {
                // 支付记录新增
                renewTuiEntity.setBatchId(batchId);
                renewTuiEntity.setCreateUserId(CommonUtils.getUserId());
                renewTuiService.save(renewTuiEntity);
            } else {
                // 支付记录修改
                renewTuiService.updateById(renewTuiEntity);
            }
            tkCount = tkCount.add(renewTuiEntity.getTkje());
        }
        return R.ok(tkCount);
    }

    @Override
    public R postSaveYzfOrder(Map map) {
        System.out.println(map);
        RenewBatchEntity renewBatch = new RenewBatchEntity();
        renewBatch.setRenewBatchId(map.get("yzfBatchId").toString());
        renewBatch.setYsfy(new BigDecimal(map.get("yzfYsfy").toString()));
        renewBatch.setYshz(new BigDecimal(map.get("yzfYshz").toString()));
        renewBatchService.updateById(renewBatch);
        List<RenewDetailsEntity> detailsList = (List<RenewDetailsEntity>) map.get("yzfList");
        ObjectMapper objectMapper = new ObjectMapper();
        for (int i = 0; i < detailsList.size(); i++) {
            RenewDetailsEntity renewDetailsEntity = objectMapper.convertValue(detailsList.get(i), RenewDetailsEntity.class);
            renewDetailsService.updateById(renewDetailsEntity);
        }
        return R.ok();
    }

    @Override
    public R postSaveDxfOrder(Map map) {
        System.out.println(map);

        Map yzfObj = (Map) map.get("yzfObj");
        Map dxfObj = (Map) map.get("dxfObj");

        RenewBatchEntity renewBatch = new RenewBatchEntity();
        renewBatch.setRenewBatchId(dxfObj.get("dxfBatchId").toString());
        if (dxfObj.get("dxfXfywkssj") != null) {
            String ywkssj = dxfObj.get("dxfXfywkssj").toString();
            renewBatch.setXfywkssj(DateUtils.stringToDate(ywkssj, DateUtils.DATE_PATTERN));
        }
        if (dxfObj.get("dxfXfywjssj") != null) {
            String ywjssj = dxfObj.get("dxfXfywjssj").toString();
            renewBatch.setXfywjssj(DateUtils.stringToDate(ywjssj, DateUtils.DATE_PATTERN));
        }
        renewBatch.setYsfy(new BigDecimal(dxfObj.get("dxfYsfy").toString()));
        renewBatch.setYshz(new BigDecimal(dxfObj.get("dxfYshz").toString()));
        renewBatchService.updateById(renewBatch);
        List<RenewDetailsEntity> detailsList = (List<RenewDetailsEntity>) dxfObj.get("dxfList");
        for (int i = 0; i < detailsList.size(); i++) {
            ObjectMapper objectMapper = new ObjectMapper();
            RenewDetailsEntity renewDetailsEntity = objectMapper.convertValue(detailsList.get(i), RenewDetailsEntity.class);
            renewDetailsService.updateById(renewDetailsEntity);
        }

        postSaveYzfOrder(yzfObj);
        return R.ok();
    }

    @Override
    @Transactional
    public R postXf(Map map1) {
        Map dxfObj = (Map) map1.get("dxfObj");
        postSaveDxfOrder(map1);
        Long dxfCustomerShopBusinessId = Long.parseLong(dxfObj.get("dxfCustomerShopBusinessId").toString());
        // 非空校验
        if (dxfObj.get("dxfXfywkssj") == null || dxfObj.get("dxfXfywjssj") == null) {
            return R.error("请输入开始日期及结束日期！");
        }

        Date xfywkssj = DateUtils.stringToDate(dxfObj.get("dxfXfywkssj").toString(), DateUtils.DATE_PATTERN);
        Date xfywjssj = DateUtils.stringToDate(dxfObj.get("dxfXfywjssj").toString(), DateUtils.DATE_PATTERN);
        // 时间校验
        if (xfywjssj.compareTo(xfywkssj) < 1) {
            return R.error("结束日期必须大于开始日期！");
        }
        // 本期的批次id
        String batchId = dxfObj.get("dxfBatchId").toString();

        // 上期的批次id
        RenewBatchEntity renewBatch = renewBatchService.getPreviousPeriodData(batchId, dxfCustomerShopBusinessId);
        String sqBatchId = renewBatch.getRenewBatchId();

        QueryWrapper<RenewDetailsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("renew_batch_id", sqBatchId);
        List<RenewDetailsEntity> sqDetailsList = renewDetailsService.list(queryWrapper);
        for (RenewDetailsEntity renewDetailsEntity : sqDetailsList) {
            Date ywjssj = renewDetailsEntity.getYwjssj();
            if (xfywkssj.compareTo(ywjssj) < 1) {
                return R.error("续费开始日期必须大于上一期的结束日期！");
            }
        }

        // 续费操作

        QueryWrapper<RenewDetailsEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("renew_batch_id", batchId);
        List<RenewDetailsEntity> bqDetailsList = renewDetailsService.list(queryWrapper1);


        BigDecimal ywdx = new BigDecimal(dxfObj.get("dxfYshz").toString());
        Integer dxfRjzxlSum = Integer.parseInt(dxfObj.get("dxfRjzxlSum").toString());
        for (RenewDetailsEntity renewDetailsEntity : bqDetailsList) {
            // 业务表 - 批量修改开始日期和结束日期,并修改在主业务的业务底薪
            CustomerShopBusinessEntity customerShopBusiness = new CustomerShopBusinessEntity();
            customerShopBusiness.setCustomerShopBusinessId(renewDetailsEntity.getCustomerShopBusinessId());
            customerShopBusiness.setYwkssj(xfywkssj);
            customerShopBusiness.setYwjssj(xfywjssj);
            customerShopBusiness.setZxl(renewDetailsEntity.getRjzxl());
            if (dxfCustomerShopBusinessId.equals(renewDetailsEntity.getCustomerShopBusinessId())) {
                customerShopBusiness.setYwdx(ywdx);
                customerShopBusiness.setZxlSum(dxfRjzxlSum);
            }
            customerShopBusinessService.updateById(customerShopBusiness);

            // 续费明细表 - 修改开始日期和结束日期
            renewDetailsEntity.setYwkssj(xfywkssj);
            renewDetailsEntity.setYwjssj(xfywjssj);
            renewDetailsService.updateById(renewDetailsEntity);
        }

        // 本期批次状态改为1,上期批次状态改为0
        RenewBatchEntity renewBatch1 = new RenewBatchEntity();
        renewBatch1.setRenewBatchId(batchId);
        renewBatch1.setRenewStatus(1);
        renewBatchService.updateById(renewBatch1);

        RenewBatchEntity renewBatch2 = new RenewBatchEntity();
        renewBatch2.setRenewBatchId(sqBatchId);
        renewBatch2.setRenewStatus(2);
        renewBatchService.updateById(renewBatch2);
        return R.ok();
    }

    @Override
    public List<RenewBatchEntity> getRenewHistoryData(Map map) {
        Long customerShopBusinessId = Long.parseLong(map.get("customerShopBusinessId").toString());
        CustomerShopBusinessEntity ywObj = customerShopBusinessService.getById(customerShopBusinessId);
        List<Integer> renewStatus = new ArrayList<>(Arrays.asList(2));
        List<RenewBatchEntity> list = renewManageTwoMapper.getRenewBatchData(ywObj, renewStatus);
        return list;
    }

    private String getBatchId() {
        String renewBatchId = UUID.randomUUID().toString().replaceAll("-", "");
        return renewBatchId;
    }
}